import { login } from '@/api/login'
import { logout, getInfo, getMenu } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, constantRoutes } from '@/router'

import Layout from '@/layout'
import store from '../index'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, grant_type, scope } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, grant_type: grant_type, scope: scope }).then(response => {
        commit('SET_TOKEN', response.access_token)
        setToken(response.access_token)
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        // const { data } = response
        //
        // if (!data) {
        //   reject('Verification failed, please Login again.')
        // }
        //
        // const { name, avatar } = data

        commit('SET_NAME', response.obj.user.username)
        commit('SET_AVATAR', '')
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 生成路由
  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      getMenu().then(response => {
        const menu = response.obj
        const asyncRoutes = convertRouter(menu)
        commit('SET_ROUTES', asyncRoutes)
        resolve(asyncRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

/**
 *将后台的路由表进行格式化
 * @param {*} asyncRouterMap
 */
export function convertRouter(asyncRouterMap) {
  const accessedRouters = []
  if (asyncRouterMap) {
    asyncRouterMap.forEach(item => {
      var parent = generateRouter(item)
      var children = []
      if (item.children) {
        item.children.forEach(child => {
          children.push(generateRouter(child))
        })
      }
      parent.children = children
      accessedRouters.push(parent)
    })
  }
  accessedRouters.push({ path: '*', redirect: '/404', hidden: true })
  return accessedRouters
}

export function generateRouter(item) {
  var router = {
    path: item.path,
    name: item.name,
    meta: { title: item.name, icon: item.icon },
    // component: item.component === 'Layout' ? Layout : getViews(item.component),
    // component: item.component === 'Layout' ? Layout : () => import(`@/views/${item.component}.vue`),
    component: item.component === 'Layout' ? Layout : () => import(`@/${item.component}.vue`),
    // redirect: item.component === 'Layout' ? 'noredirect' :  '',
    // 面包屑上 点击 redirect 的 url  首页/系统管理/菜单管理  , 可点击系统管理
    redirect: item.redirect ? item.redirect : item.component === 'Layout' ? 'noredirect' : '',
    // component: isParent ? Layout : componentsMap[item.name],
    // alwaysShow: item.children.length === 1 ? true : false
    alwaysShow: item.children.length === 1
  }
  // console.log('router....', router)
  return router
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

